package com.smallbeef.springboot_demo.controller;

import com.smallbeef.springboot_demo.bean.Department;
import com.smallbeef.springboot_demo.bean.Employee;
import com.smallbeef.springboot_demo.dao.DepartmentDao;
import com.smallbeef.springboot_demo.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao; // 因为没有数据库，所有数据库都定义在 Dao 层里面了

    @Autowired
    DepartmentDao departmentDao;

    // 显示所有员工信息
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    // 跳转到员工添加界面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        // 查出所有部门信息
        Collection<Department> departments = departmentDao.getDepartment();
        model.addAttribute("departments",departments); // 存入model 使得前端能够获取
        return "emp/add";
    }

    // 添加员工
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee); // 添加员工信息
        return "redirect:/emps"; // 跳转到首页
    }

    // 跳转到修改员工界面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
        //查出原来的数据
        System.out.println(id);
        Employee employee = employeeDao.getEmployeeById(id);
        System.out.println(employee);
        model.addAttribute("emp",employee);
        //查询所有部门信息
        Collection<Department> departments=departmentDao.getDepartment();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    // 修改员工
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeDao.save(employee); // 保存员工信息
        return "redirect:/emps"; // 跳转到首页
    }

    // 删除员工
    @GetMapping("/delemp/{id}")
    public String toDeleteEmp(@PathVariable("id")Integer id){
        System.out.println(id);
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    // 登出
    @RequestMapping("/user/logout")
    public String UserLogout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }

}
